<template>
  <div class="message-template-view">
    <h1>消息模板管理</h1>
    <div class="toolbar">
      <el-button type="primary" @click="openCreateDialog">新增模板</el-button>
      <el-input
          v-model="searchQuery"
          placeholder="搜索模板"
          clearable
          style="width: 300px; margin-left: 20px;"
          @input="handleSearch"
      />
    </div>

    <el-table :data="messageTemplates" style="width: 100%; margin-top: 20px;" stripe>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="title" label="标题"></el-table-column>
      <el-table-column prop="content" label="内容"></el-table-column>
      <el-table-column prop="message_type" label="类型" width="100"></el-table-column>
      <el-table-column prop="platform" label="平台" width="120"></el-table-column>
      <el-table-column prop="creator_id" label="创建者" width="100"></el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="wechat_tpl_id" label="模板ID" width="180"></el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          <el-button type="success" size="small" @click="openPushDialog(scope.row)">推送</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增模板 Dialog -->
    <el-dialog title="新增消息模板" v-model="createDialogVisible">
      <el-form :model="createForm" ref="createFormRef" label-width="100px">
        <el-form-item
            label="标题"
            prop="title"
            :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
        >
          <el-input v-model="createForm.title" />
        </el-form-item>
        <el-form-item
            label="内容"
            prop="content"
            :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
        >
          <el-input type="textarea" v-model="createForm.content" />
        </el-form-item>
        <el-form-item
            label="类型"
            prop="message_type"
            :rules="[{ required: true, message: '请选择类型', trigger: 'change' }]"
        >
          <el-select v-model="createForm.message_type" placeholder="请选择类型">
            <el-option label="通知" value="通知"></el-option>
            <el-option label="提醒" value="提醒"></el-option>
            <el-option label="公告" value="公告"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            label="平台"
            prop="platform"
            :rules="[{ required: true, message: '请输入平台', trigger: 'blur' }]"
        >
          <el-input v-model="createForm.platform" />
        </el-form-item>
        <el-form-item
            label="模板ID"
            prop="wechat_tpl_id"
            :rules="[{ required: true, message: '请输入微信模板ID', trigger: 'blur' }]"
        >
          <el-input v-model="createForm.wechat_tpl_id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="createDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitCreate">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑模板 Dialog -->
    <el-dialog title="编辑消息模板" v-model="editDialogVisible">
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item
            label="标题"
            prop="title"
            :rules="[{ required: true, message: '请输入标题', trigger: 'blur' }]"
        >
          <el-input v-model="editForm.title" />
        </el-form-item>
        <el-form-item
            label="内容"
            prop="content"
            :rules="[{ required: true, message: '请输入内容', trigger: 'blur' }]"
        >
          <el-input type="textarea" v-model="editForm.content" />
        </el-form-item>
        <el-form-item
            label="类型"
            prop="message_type"
            :rules="[{ required: true, message: '请选择类型', trigger: 'change' }]"
        >
          <el-select v-model="editForm.message_type" placeholder="请选择类型">
            <el-option label="通知" value="通知"></el-option>
            <el-option label="提醒" value="提醒"></el-option>
            <el-option label="公告" value="公告"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
            label="平台"
            prop="platform"
            :rules="[{ required: true, message: '请输入平台', trigger: 'blur' }]"
        >
          <el-input v-model="editForm.platform" />
        </el-form-item>
        <el-form-item
            label="模板ID"
            prop="wechat_tpl_id"
            :rules="[{ required: true, message: '请输入微信模板ID', trigger: 'blur' }]"
        >
          <el-input v-model="editForm.wechat_tpl_id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 定向推送 Dialog -->
    <el-dialog title="定向推送消息" v-model="pushDialogVisible">
      <el-form :model="pushForm" ref="pushFormRef" label-width="120px">
        <el-form-item label="微信模板ID">
          <el-input v-model="pushForm.wechat_tpl_id" disabled />
        </el-form-item>
        <el-form-item label="推送角色">
          <el-select v-model="pushForm.role" placeholder="选择用户角色">
            <el-option label="开放推送" value="开放推送"></el-option>
            <el-option label="关闭推送" value="关闭推送"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="指定用户ID">
          <el-input v-model="pushForm.userIds" placeholder="多个ID以逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="pushDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitPush">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'

// 消息模板数据
const messageTemplates = ref([])
const searchQuery = ref("")

// Dialog 显示标志
const createDialogVisible = ref(false)
const editDialogVisible = ref(false)
const pushDialogVisible = ref(false)

// 表单引用
const createFormRef = ref(null)
const editFormRef = ref(null)
const pushFormRef = ref(null)

// 新增表单数据
const createForm = reactive({
  title: '',
  content: '',
  message_type: '',
  platform: '',
  wechat_tpl_id: '',
})

// 编辑表单数据
const editForm = reactive({
  id: null,
  title: '',
  content: '',
  message_type: '',
  platform: '',
  wechat_tpl_id: '',
})

// 定向推送表单数据
const pushForm = reactive({
  wechat_tpl_id: '',
  role: '',
  userIds: '',
})

// 获取消息模板列表
const fetchTemplates = async () => {
  try {
    let url = 'https://8223yt8md244.vicp.fun/api/message_templates'
    if (searchQuery.value.trim() !== "") {
      url += `?q=${encodeURIComponent(searchQuery.value.trim())}`
    }
    const res = await fetch(url)
    const data = await res.json()
    if (res.ok) {
      messageTemplates.value = data.templates
    } else {
      ElMessage.error(data.error || '获取消息模板失败')
    }
  } catch {
    ElMessage.error('网络错误')
  }
}

onMounted(fetchTemplates)

// 搜索模板
const handleSearch = () => {
  fetchTemplates()
}

// 打开新增模板 Dialog
const openCreateDialog = () => {
  Object.assign(createForm, {
    title: '',
    content: '',
    message_type: '',
    platform: '',
    wechat_tpl_id: '',
  })
  createDialogVisible.value = true
}

// 提交新增模板
const submitCreate = async () => {
  createFormRef.value.validate(async valid => {
    if (!valid) return
    try {
      const res = await fetch('https://8223yt8md244.vicp.fun/api/message_templates', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(createForm)
      })
      const data = await res.json()
      if (res.ok) {
        ElMessage.success('创建成功')
        createDialogVisible.value = false
        fetchTemplates()
      } else {
        ElMessage.error(data.error || '创建失败')
      }
    } catch {
      ElMessage.error('网络错误')
    }
  })
}

// 打开编辑 Dialog，并填充数据
const openEditDialog = row => {
  Object.assign(editForm, {
    id: row.id,
    title: row.title,
    content: row.content,
    message_type: row.message_type,
    platform: row.platform,
    wechat_tpl_id: row.wechat_tpl_id,
  })
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  editFormRef.value.validate(async valid => {
    if (!valid)
    try {
      const res = await fetch(`https://8223yt8md244.vicp.fun/api/message_templates/${editForm.id}`, {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(editForm)
      })
      const data = await res.json()
      if (res.ok) {
        ElMessage.success('更新成功')
        editDialogVisible.value = false
        fetchTemplates()
      } else {
        ElMessage.error(data.error || '更新失败')
      }
    } catch {
      ElMessage.error('网络错误')
    }
  })
}

// 删除模板
const handleDelete = row => {
  ElMessageBox.confirm('此操作将软删除该模板，是否继续？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const res = await fetch(`https://8223yt8md244.vicp.fun/api/message_templates/${row.id}`, {
        method: 'DELETE'
      })
      const data = await res.json()
      if (res.ok) {
        ElMessage.success('删除成功')
        fetchTemplates()
      } else {
        ElMessage.error(data.error || '删除失败')
      }
    } catch {
      ElMessage.error('网络错误')
    }
  }).catch(() => {
  })
}

// 打开定向推送 Dialog
const openPushDialog = row => {
  pushForm.wechat_tpl_id = row.wechat_tpl_id
  pushForm.role = ''
  pushForm.userIds = ''
  pushDialogVisible.value = true
}

// 提交推送
// 提交推送
const submitPush = async () => {
  // 去掉类型注解，改成下面这样：
  let userIdsArray = [];
  if (pushForm.userIds.trim()) {
    userIdsArray = pushForm.userIds
        .split(',')
        .map(id => parseInt(id.trim()))
        .filter(id => !isNaN(id));
  }
  try {
    const res = await fetch('https://8223yt8md244.vicp.fun/api/message_templates/push', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        wechat_tpl_id: pushForm.wechat_tpl_id,
        role: pushForm.role,
        user_ids: userIdsArray
      })
    });
    const data = await res.json();
    if (res.ok) {
      ElMessage.success('推送成功');
      pushDialogVisible.value = false;
    } else {
      ElMessage.error(data.error || '推送失败');
    }
  } catch {
    ElMessage.error('网络错误');
  }
};

</script>

<style scoped>
.message-template-view {
  padding: 20px;
}

.toolbar {
  display: flex;
  align-items: center;
}

.dialog-footer {
  text-align: right;
}
</style>
